/*
 * Project Name spring-boot-tools
 * File Name SseEmitterUtil
 * Package Name com.huxiaotu.tools.sse.utils
 * Create Time 2024/7/26
 * Create by name：liujie
 */
package com.huxiaotu.tools.sse.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/26 10:34
 */
@Slf4j
public class SseEmitterUtil {
    static Map<String, SseEmitter> allSession = new HashMap<>();
    public static void eventListener(String sessionId,SseEmitter sseEmitter ){
        sseEmitter.onCompletion(() -> log.info("[{}] emitter completed",sessionId));
        sseEmitter.onError(throwable ->  log.info("[{}] emitter error",sessionId));
        sseEmitter.onTimeout(() ->  log.info("[{}] emitter timeout",sessionId));
        SseEmitterUtil.addSession(sessionId,sseEmitter);
    }


    public static void addSession(String sessionId,SseEmitter sseEmitter ){
        allSession.put(sessionId,sseEmitter);
    }

    public static void sendMsg(String sessionId,String message){
        SseEmitter sseEmitter = getSession(sessionId);
        try {
            sseEmitter.send(message);
            Thread.sleep(123);
        } catch (Exception e) {
            sseEmitter.completeWithError(e);
            log.error("textGenerator error {}",e.getMessage());
        }
    }


    public static void completed(String sessionId){
        getSession(sessionId).complete();
    }


    public static SseEmitter getSession(String sessionId){
        return allSession.get(sessionId);
    }
}